<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\model\Activity as ActivityModel;
use app\common\model\ActivityOrder;
use app\common\model\User;
use think\Exception;

/**
 * 首页接口
 */
class Activity extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 活动列表
     * @return void
     */
    public function getList()
    {
        $verification_user_ids = $this->request->post('verification_user_id');
        $map = [];
        if($verification_user_ids){
            $map['verification_user_ids'] = $verification_user_ids;
        }
        $list = ActivityModel::where('status',1)->where($map)->order("weigh desc")->paginate()->each(function ($item){
            $item['order_num'] = ActivityOrder::where('activity_id',$item['id'])->where('status','in',[1,2])->count();
            return $item;
        });
        $this->success('ok',$list);
    }



    /**
     * 活动详情
     * @return void
     */
    public function getDetail()
    {
        $id = $this->request->post('id');
        $detail = ActivityModel::get($id);
        $this->success('ok',$detail);
    }

    /**
     * 预约提交
     * @return void
     */
    public function addOrder()
    {
        $activity_id = $this->request->post('activity_id');
        $pay_type = $this->request->post('pay_type');
        $activity = ActivityModel::get($activity_id);
        if(!$activity){
            $this->error('活动不存在');
        }
        if($activity['status'] != 1){
            $this->error('活动状态错误');
        }
        //查询此用户是否已经预约过此活动
        $is_order = ActivityOrder::where('user_id',$this->auth->id)->where('activity_id',$activity_id)->where('status','in',[1,2])->find();
        if($is_order){
            $this->error('您已经预约过此活动');
        }
        //查询此订单预约人数
        $order_num = ActivityOrder::where('activity_id',$activity_id)->where('status','in',[0,1,2])->count();
        if($order_num >= $activity->max_count){
            $this->error('预约人数已满1');
        }
        $data = [
            'order_no'=>date('YmdHis').mt_rand(1000,9999),
            'activity_id' => $activity_id,
            'user_id' => $this->auth->id,
            'total_price'=>$activity->price,
            'pay_type'=>$pay_type,
            'verification_code'=>mt_rand(10000000,99999999).$activity_id.$this->auth->id,
            'status'=>0,
            'createtime'=>time(),
            'updatetime'=>time(),
        ];
        if($activity->price == 0){
            $order = ActivityOrder::create($data);
            //直接回调
            ActivityOrder::paysuccess($order->order_no,$activity->price,'score');
            $this->success('ok',$order);
        }else{
            //积分支付
            if($pay_type == 'score'){
                //查询积分是否充足
                if($this->auth->score < $activity->price){
                    $this->error('积分不足');
                }
                try{
                    Db::startTrans();
                    $order = ActivityOrder::create($data);
                    //扣除积分
                    User::score(-$activity->price, $this->auth->id, '活动预约');
                    //直接回调
                    ActivityOrder::paysuccess($order->order_no,$activity->price,'score');
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('ok',$order);
            }else{
                $order = ActivityOrder::create($data);
                $request = \think\Request::instance();
                $notifyurl = $request->root(true) . '/api/activity/epay/type/notify/paytype/' . 'wechat';
                $params = [
                    'amount'=>$activity->price,
                    'orderid'=>$order->order_no,
                    'type'=>"wechat",
                    'title'=>"活动预约",
                    'notifyurl'=>$notifyurl,
//                'returnurl'=>"返回地址",
                    'method'=>"miniapp",
                    'openid'=>$this->auth->openid,
                ];
                $res = \addons\epay\library\Service::submitOrder($params);
                $this->success('ok',$res);
            }
        }


    }

    /**
     * 企业支付通知和回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
//                \addons\recharge\library\Order::settle($data['out_trade_no'], $payamount);
                //直接回调
                ActivityOrder::paysuccess($data['out_trade_no'],$payamount,'wechat');
            } catch (Exception $e) {
            }
            return $pay->success()->send();
        } else {
//            $pay = \addons\epay\library\Service::checkReturn($paytype);
//            if (!$pay) {
//                $this->error('签名错误');
//            }
//            //微信支付没有返回链接
//            if ($pay === true) {
//                $this->success("请返回网站查看支付状态!", "");
//            }

            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
            $this->success("恭喜你！充值成功!", url("user/index"));
        }
        return;
    }

    /**
     * 订单列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function getOrderList()
    {
        $status = $this->request->post('status');
        $activity_id = $this->request->post('activity_id');
        $is_verification = $this->request->post('is_verification');


        $map = [];
        if($status){
            $map['status'] = ['in',$status];
        }
        $user_map = [];
        if($is_verification != 1){
            $user_map['user_id'] = $this->auth->id;
        }

        if($activity_id){
            $map['activity_id'] = $activity_id;
        }
        $status1 = ActivityOrder::where($user_map)->where('status','neq',0)->where('status',1)->count();
        $status2 = ActivityOrder::where($user_map)->where('status','neq',0)->where('status',2)->count();
        $all = ActivityOrder::where($user_map)->where('status','neq',0)->count();
        $list = ActivityOrder::where($user_map)
            ->where('status','neq',0)
            ->where($map)
            ->order('createtime desc')->paginate()->each(function ($item){
                $item->activity = ActivityModel::where('id',$item['activity_id'])->find();
                $item->order_num = ActivityOrder::where('activity_id',$item['activity_id'])->where('status','in',[1,2])->count();
                $item['user'] = User::where('id',$item['user_id'])->field('id,nickname,avatar,mobile')->find();
                return $item;
            });
        $this->success('ok',['count'=>['all'=>$all,'status1'=>$status1,'status2'=>$status2],'list'=>$list]);
    }

    /**
     * 订单详情
     * @return void
     */
    public function getOrderDetail()
    {
        $order_id = $this->request->post('order_id');
        $order = ActivityOrder::get($order_id);
        if(!$order){
            $this->error('订单不存在');
        }
//        if($order['user_id'] != $this->auth->id){
//            $this->error('您无权查看此订单');
//        }
        $order['user'] = User::where('id',$order['user_id'])->field('id,nickname,avatar,mobile')->find();
        $order['activity'] = ActivityModel::where('id',$order['activity_id'])->find();
        $order['order_num'] = ActivityOrder::where('activity_id',$order['activity_id'])->where('status','in',[1,2])->count();
        $url = '/pages-merchant/order/cancelAfterVerification?id='.$order['id'];
        $order['verification_img'] = '/qrcode/build?text='.$url;
        $this->success('ok',$order);
    }

    /**
     * 订单核销
     * @return void
     */
    public function orderVerification()
    {
        $code = $this->request->post('verification_code');
        $order = ActivityOrder::get(['verification_code'=>$code]);
        if(!$order){
            $this->error('订单不存在');
        }
        $activity = ActivityModel::get($order->activity_id);
        //查询是否有核销权限
        $user_all = explode(',',$activity->verification_user_ids);
        if(!in_array($this->auth->id,$user_all)){
            $this->error('您无权核销此订单');
        }
        $order->verification_time = time();
        $order->verification_user_id = $this->auth->id;
        $order->status = 2;
        if($order->save()){
            $this->success('核销成功',$order);
        }else{
            $this->error('核销失败');
        }

    }

    /**
     * 取消订单
     * @return void
     */
    public function cancelOrder()
    {
        $order_id = $this->request->post('order_id');
        $order = ActivityOrder::get($order_id);
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['user_id'] != $this->auth->id){
            $this->error('您无权取消此订单');
        }
        if($order['status'] != 1){
            $this->error('订单状态错误');
        }
        if((time() - $order->createtime) > config('site.cancel_activity') * 60 * 60){
            $this->error('订单已超过可取消时间');
        }
        $order->status = 3;
        $order->cancel_time = time();
        if($order->pay_type == 'wechat'){
            $this->error('暂未开放');
        }
        if($order->save()){
            if($order->pay_type == 'score'){
                User::score($order->score_fee, $this->auth->id, '订单取消返还金额');
            }
            $this->success('取消成功',$order);
        }else{
            $this->error('取消失败');
        }
    }
}
